﻿using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid; 
using eFatura.Utility;
using eFatura.Utility.Grid; 
using Extensions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using eFatura.Utility.Ribbon;
using DevExpress.Data;

namespace eFatura
{
    public partial class XForm : DevExpress.XtraEditors.XtraForm
    {
        public int WhoAmI
        {
            get
            {
                return AppSession.UserInfo.UserId;
            }
        }

        public string Schema
        {
            get
            {
                return AppSession.Schema;
            }
        }

        public int SirketId
        {
            get
            {
                return AppSession.SirketId;
            }
        }

        public bool isYonetici
        {
            get
            {
                return AppSession.UserInfo.Yonetici;
            }
        } 

        string adet = "Count: ";
        string toplam = "Sum: ";

        public XForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterParent;
        }

        void gridview_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            GridView g = sender as GridView;
            DevExpress.XtraGrid.Views.Base.GridCell[] cells = g.GetSelectedCells();
            if (cells.Length == 0)
                return;

            double sum = 0;

            foreach (DevExpress.XtraGrid.Views.Base.GridCell gc in cells)
            {
                double val = 0.0;
                string cellVal = g.GetRowCellDisplayText(gc.RowHandle, gc.Column);
                CultureInfo ci = Application.CurrentCulture;
                double.TryParse(cellVal, NumberStyles.Any, ci, out val);

                sum += val;
            }

            adet = string.Format("{0}{1:n0}", "Count: ", cells.Length);

            if (sum > 0)
                toplam = string.Format("{0}{1:n1}", "Sum: ", sum);
            else
                toplam = "";

            AppSession.MainForm.NotifySelectionInfo(this);
        }

        string selectionInfo = "";
        public string SelectionInfo
        {
            get
            {
                string seperator = "  " + ((char)183) + "  ";
                List<string> result = new List<string>();

                result.Add(adet);

                if (toplam != "")
                    result.Add(toplam);

                if (selectionInfo != "")
                    result.Add(selectionInfo);

                return string.Join(seperator, result.ToArray());
            }
            set
            {
                selectionInfo = value;
                AppSession.MainForm.NotifySelectionInfo(this);
            }
        }

        protected void EndGridViewEdit(GridView view)
        {
            view.CloseEditor();
            view.UpdateCurrentRow();
        }

        public void ShowOnlyBar()
        {
            HeaderPanel.Visible = false;
            MainToolbar.Visible = true;
        }

        public void InitGridView(GridView gridview, BindingSource bs, bool initialized = false)
        {
            try
            {
                gridview.GridControl.MenuManager = barManager;
                gridview.SelectionChanged -= gridview_SelectionChanged;
                gridview.SelectionChanged += gridview_SelectionChanged;
                gridview.BeginUpdate();
                gridview.Columns.Clear();
                if (bs != null)
                {
                    gridview.GridControl.DataSource = null;
                    gridview.GridControl.DataSource = bs;
                    gridview.PopulateColumns();
                }
                if (gridview.ViewCaption == string.Empty)
                    gridview.ViewCaption = gridview.Name;


                foreach (GridColumn col in gridview.Columns)
                {
                    if (col.FieldName != bs.DataMember + "Id")
                        MapGridColumn(col);
                    else
                    {
                        col.OptionsColumn.AllowEdit = false;
                        col.AppearanceCell.BackColor = System.Drawing.Color.LightYellow;
                    }

                    if (col.ColumnType == Type.GetType("System.Boolean"))
                    {
                        RepositoryItemCheckEdit ri = new RepositoryItemCheckEdit();
                        ri.AllowGrayed = false;
                        col.ColumnEdit = ri;
                    }
                    else if (col.ColumnType == typeof(DateTime))
                    {
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.DateSmart;
                        col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
                        col.OptionsFilter.ImmediateUpdateAutoFilter = true;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnCheck = DevExpress.Utils.DefaultBoolean.True;
                        col.OptionsFilter.ImmediateUpdatePopupDateFilterOnDateChange = DevExpress.Utils.DefaultBoolean.True;
                    }
                    else if (col.ColumnEdit is RepositoryItemGridLookUpEdit)
                        col.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;
                }

                gridview.BestFitMaxRowCount = 200;
                gridview.GridControl.ShowOnlyPredefinedDetails = true;
                gridview.HorzScrollStep = 50;
                gridview.NewItemRowText = "Click to add new row";
                gridview.OptionsBehavior.CopyToClipboardWithColumnHeaders = false;
                gridview.OptionsBehavior.EditorShowMode = EditorShowMode.Default;
                gridview.OptionsBehavior.ImmediateUpdateRowPosition = false;
                gridview.OptionsBehavior.KeepFocusedRowOnUpdate = true;
                gridview.OptionsFilter.AllowColumnMRUFilterList = true;
                gridview.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;
                gridview.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
                gridview.OptionsHint.ShowColumnHeaderHints = true;
                gridview.OptionsMenu.EnableColumnMenu = true;
                gridview.OptionsMenu.ShowDateTimeGroupIntervalItems = true;
                gridview.OptionsNavigation.UseOfficePageNavigation = true;
                gridview.OptionsSelection.MultiSelect = true;
                gridview.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
                gridview.OptionsView.ColumnAutoWidth = false;
                gridview.OptionsView.EnableAppearanceEvenRow = true;
                gridview.OptionsView.RowAutoHeight = true;
                gridview.OptionsView.ShowAutoFilterRow = true;
                gridview.OptionsView.ShowDetailButtons = false;
                gridview.OptionsView.ShowGroupPanel = false;
                gridview.ViewCaption = gridview.ViewCaption.Replace("gv", string.Empty);

                foreach (GridColumn gc in gridview.Columns)
                {
                    string colName = gc.FieldName.ToLower();
                    if (colName == "modifiedon" || colName == "ts" || colName == "deleted")
                        gc.Visible = false;
                    else
                        gc.Visible = true;
                }
                GridManager.GetManager(gridview);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                gridview.EndUpdate();
            }
        }
         
        public void MapGridColumn(GridColumn col)
        {
            string fieldName = col.FieldName;

            col.FilterMode = ColumnFilterMode.DisplayText;

            col.OptionsColumn.AllowEdit = true;     // col.FieldName != "UserId";    //userId sonradan değiştirilemesin diye!

            RepositoryItem ri = GetFieldRI(fieldName);
            if (ri != null)
                col.ColumnEdit = ri;
            else if (col.ColumnType == typeof(String))
                col.ColumnEdit = new RepositoryItemTextEdit();

            switch (fieldName)
            {
                default:
                    if (fieldName.IndexOf("qty") > -1 || ";bol;kalan;ordermt;gelenmt;beklenenmt;yuklenenmt;metre;adet;eksik;alt;ust;fark;gelenmetre;cikanmetre;toplam;toplamyuklenenmt;toplammt;toplamfark;siparisedilenmt;toplamsiparismiktar;toplamsipmiktari;toplamgelenmiktar;yuklenengelenmiktar;ayrimmt;mt;yuklenenmt;depoyagelenmt;otherquantities;reorderpoint;percentage;metraj;en;point;".Contains(";" + fieldName + ";"))
                        col.FormatAsNumber(0);
                    else if (";fiyat;hedeffiyat;anlasilanfiyat;xanlasilanfiyat;faturafiyati;xfaturafiyati;birimfiyat;unitprice;latestunitprice;price;price_;cost;balance;linetotal;subtotal;discount;grandtotal;taxamt;freight;".Contains(";" + fieldName + ";"))
                        col.FormatAsNumber(2);

                    break;
            }
        }
         
        public RepositoryItem GetFieldRI(string fieldName)
        {

            fieldName = fieldName.ToLower();

            if (fieldName.EndsWith("Id".ToLower()))
            {
                fieldName = fieldName
                                        .Substring(0, fieldName.Length - 2)
                                        .Replace("latest", "")
                                        .Replace("prf", "");
                switch (fieldName)
                {
                    /*
                case "cari": return RI(Rp.Cari);
                    
                case "kumashatatipi": return RI(Rp.KumasHataTipi);
                case "sevkiyatci": return RI(Rp.Sevkiyatci);
                */
                    default: return null;
                }
            }
            else
            {
                switch (fieldName)
                {

                    default:
                        if (fieldName.IndexOf("qty") > -1 || ";bol;kalan;ordermt;gelenmt;beklenenmt;yuklenenmt;metre;adet;eksik;alt;ust;fark;gelenmetre;cikanmetre;toplam;toplamyuklenenmt;toplammt;toplamfark;siparisedilenmt;toplamsiparismiktar;toplamsipmiktari;toplamgelenmiktar;yuklenengelenmiktar;ayrimmt;mt;yuklenenmt;depoyagelenmt;otherquantities;reorderpoint;percentage;metraj;en;point;".Contains(";" + fieldName + ";"))
                        {
                            return new RepositoryItemCalcEdit();
                        }
                        return null;
                }
            }
        }
         
        public static void SetSplitterPosition(SplitContainerControl scc, float payda = 2)
        {
            scc.SplitterPosition = (int)((scc.Horizontal ? scc.Width : scc.Height) / payda);
        }

        public virtual void MySizeChanged(object sender, EventArgs e)
        {
            //SplitContainerControl scc = ((SplitContainerControl)sender);
            //scc.SizeChanged -= sizeChanged;
            SetSplitterPosition(sender as SplitContainerControl);
            //scc.SplitterPosition = (scc.Horizontal ? scc.Width : scc.Height) / 2;
        }
         
        public static void Notify(string str)
        {
            eFatura.Utility.AppSession.MainForm.NotifyMain(str);
        }
         
        private void XForm_Load(object sender, EventArgs e)
        {
            HeaderPanel.Visible = false;
            MainToolbar.Visible = false;
        }
    }
}